package com.bawei.library_network.factory

import androidx.lifecycle.LiveData
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**

 * @Author : ytx

 * @Time : On 2023/5/20 08:19

 * @Description : LiveDataCallAdapterFactory

 */

class LiveDataCallAdapterFactory:CallAdapter.Factory() {
    companion object{
        fun create():LiveDataCallAdapterFactory{
            return LiveDataCallAdapterFactory()
        }
    }
    override fun get(
        returnType: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit,
    ): CallAdapter<*, *>? {
        //returnType：LiveData<ApiResponse<MutableList<BannerEntity>>>
        //判断类型是否为LiveData
        if(getRawType(returnType) != LiveData::class.java){
            return null
        }
        //获得里面的第一个泛型ApiResponse
        var observerType = getParameterUpperBound(0, returnType as ParameterizedType)
        // 第一个泛型ApiResponse的具体类型
        var rawType =  getRawType(observerType)
        if(rawType != ApiResponse::class.java){
            throw IllegalArgumentException("type must be ApiResponse")
        }
        //ApiResponse必须是一个参数化类型ParameterizedType，就看里面是不是继续有泛型
        if(!ParameterizedType::class.java.isInstance(observerType)){
            throw IllegalArgumentException("resource must be Parameterized")
        }
        return LiveDataCallAdapter<Any>(observerType)

    }
}